jQuery(document).ready(function() {
	///// SELECT WITH SEARCH /////
	jQuery(".chzn-select").chosen();
	var id = getQueryString("classroom");
	jQuery('#classroomSelect').val(id).trigger('liszt:updated');
	
	
	function getQueryString(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
		var r = window.location.search.substr(1).match(reg);
		if (r != null) return unescape(r[2]); return null;
	}

	/* initialize the calendar */
	jQuery('#calendar').fullCalendar({
		header : {
			left : 'month,agendaWeek,agendaDay',
			center : 'title',
			right : 'today, prev, next'
		},
		
		monthNames : [ "一月", "二月", "三月", "四月",
				"五月", "六月", "七月", "八月", "九月",
				"十月", "十一月", "十二月" ],
		monthNamesShort : [ "一月", "二月", "三月",
				"四月", "五月", "六月", "七月", "八月",
				"九月", "十月", "十一月", "十二月" ],
		dayNames : [ "周日", "周一", "周二", "周三",
				"周四", "周五", "周六" ],
		dayNamesShort : [ "周日", "周一", "周二",
				"周三", "周四", "周五", "周六" ],
		today : [ "今天" ],
		firstDay : 1,
		allDaySlot : false,
		axisFormat : "第H节",
		timeFormat: "第H节",
		slotDuration : "01:00:00",
		minTime : "01:00:00",
		maxTime : "14:00:00",
		buttonText : {
			prev : '&laquo;',
			next : '&raquo;',
			prevYear : '&nbsp;&lt;&lt;&nbsp;',
			nextYear : '&nbsp;&gt;&gt;&nbsp;',
			today : '今天',
			month : '月',
			week : '周',
			day : '日'
		},
		dayClick: function (date, allDay, jsEvent, view) {//日期点击后弹出的jq ui的框，添加日程记录
			var classroomId = jQuery("#classroomSelect").val();
			if(classroomId==null ||classroomId=="") {
				jQuery.jGrowl("清先在左上角选择教室！！！");
				return;
			}
			
			var selectdate = jQuery.fullCalendar.formatDate(date, "yyyy-MM-dd");//选择当前日期的时间转换
			var nowdate = jQuery.fullCalendar.formatDate(new Date(), "yyyy-MM-dd");
			if(selectdate < nowdate) {
				jQuery.jGrowl("只能预约今天及以后的！！！");
				return;
			}
			var isAdmin = jQuery("#isAdmin").val();
			if(isAdmin != "true" && selectdate > getNextMonth(nowdate)) {
				jQuery.jGrowl("只能预约一个月之内的！！！");
				return;
			}
			jQuery("#orderDate").removeAttr("disabled");
        	jQuery("#weekCorse").removeAttr("disabled");
        	jQuery("#order_type").removeAttr("disabled");
        	jQuery("#comment").removeAttr("disabled");
			var classroomId = jQuery("#classroomSelect").val();
			jQuery("#classroomId").val(classroomId);
			var classroom = jQuery("#classroomSelect_chzn span").text();
			jQuery("#orderDate").val(selectdate);
			jQuery("#classroom").val(classroom);
			jQuery("#order_type").val("");
			jQuery("#comment").val("");
			jQuery(".cancel_btn, .check_yes, .check_no").hide();
			jQuery(".order_btn").show();
			if(view.name == "month") {
				jQuery.ajax({
		        	type:"post",
		        	dataType:"json",
		        	url:"/cms/order/courses",
		        	async:true,
		        	data:{classroom:classroomId, orderDate:selectdate},
		        	success:function(data) {
		        		jQuery("#course_select_chzn").remove();
		        		jQuery("#course_select").remove();
		        		jQuery("span.formwrapper").append('<select data-placeholder="请选择课时..." name="orderCourses" id="course_select" class="chzn-select" multiple="multiple" style="width:350px;" tabindex="4">dddafafda</select>');
		        		jQuery.each(data.courses, function (index, course) {
		        			jQuery("#course_select").append("<option value="+ course.id + ">" + course.courseItem +"</option>");
		                });
		        		jQuery("#course_select").chosen();
		        	}
		        });
				jQuery("#weekCourse").hide();
				jQuery("#monthCourses").show();
				jQuery('#course_select').val('').trigger('liszt:updated');   //清空课程select
				jQuery("#classroomOrder_dialog").dialog({
					width : 500,
					modal : true
				});
			} else {
				jQuery("#weekCourse").show();
				jQuery("#monthCourses").hide();
				var weekCourse = jQuery.fullCalendar.formatDate(date, "H");
				jQuery("#weekCorse").val("第" + weekCourse + "节");
				jQuery("#weekCorse").attr("num",weekCourse);
				if(view.name == "agendaWeek") {
					jQuery("#classroomOrder_dialog").dialog({
						width : 500,
						modal : true,
					});
					
				}
			}
        },
        
        eventClick: function(calEvent, jsEvent, view) {
        	//根据id设置
        	jQuery(".order_btn").hide();
        	jQuery("#orderDate").attr("disabled", "disabled");
        	jQuery("#weekCorse").attr("disabled", "disabled");
        	jQuery("#order_type").attr("disabled", "disabled");
        	jQuery("#comment").attr("disabled", "disabled");
        	//根据id 发ajax 获得信息
        	var isAdmin = jQuery("#isAdmin").val();
            if(calEvent.backgroundColor == 'red') {   //审核
            	if(isAdmin == "true") {
            		jQuery(".check_yes, .check_no, .cancel_btn").show();
            	} else {
            		jQuery(".cancel_btn").show();
            		jQuery(".check_yes, .check_no").hide();
            	}
            	
            } else {
            	jQuery(".check_yes, .check_no, .cancel_btn").hide();
            	if(isAdmin == "true") {
            		jQuery(".cancel_btn").show();
            	}
            }
            jQuery("#weekCourse").show();
			jQuery("#monthCourses").hide();
			
			var id = calEvent.id;
			jQuery("#order_id").val(id);
			jQuery.ajax({
	        	type:"post",
	        	dataType:"json",
	        	url:"/cms/order/orderInfo",
	        	async:true,
	        	data:{id:id},
	        	success:function(data) {
	        		var order = data.order;
	        		var classroomOrder = jQuery.parseJSON(order);
	        		jQuery("#weekCorse").val(classroomOrder.course.courseItem);
	            	jQuery("#order_type").val(classroomOrder.orderType.id)
	            	jQuery("#comment").val(classroomOrder.comment);
	        		jQuery("#orderDate").val(classroomOrder.orderDate);
	        	}
	        })
			
			jQuery("#classroomOrder_dialog").dialog({
				width : 500,
				modal : true
			});
            
        }
	});
	
	jQuery.ajax({
    	type:"post",
    	dataType:"json",
    	url:"/cms/order/events",
    	async:true,
    	data:{classroom:id},
    	success:function(data) {
    		var resultCollection = jQuery.parseJSON(data.events);
            jQuery.each(resultCollection, function (index, term) {
            	jQuery("#calendar").fullCalendar('renderEvent', term, true);
            });
    	}
    });
	
	/**
	 * 获取下一个月
	 * @date 格式为yyyy-mm-dd的日期，如：2014-01-25
	 */
	 function getNextMonth(date) {
         var arr = date.split('-');
         var year = arr[0]; //获取当前日期的年份
         var month = arr[1]; //获取当前日期的月份
         var day = arr[2]; //获取当前日期的日
         var days = new Date(year, month, 0);
         days = days.getDate(); //获取当前日期中的月的天数
         var year2 = year;
         var month2 = parseInt(month) + 1;
         if (month2 == 13) {
             year2 = parseInt(year2) + 1;
             month2 = 1;
         }
         var day2 = day;
         var days2 = new Date(year2, month2, 0);
         days2 = days2.getDate();
         if (day2 > days2) {
             day2 = days2;
         }
         if (month2 < 10) {
             month2 = '0' + month2;
         }
         var t2 = year2 + '-' + month2 + '-' + day2;
         return t2;
     }
	
	jQuery("#classroom_btn").click(function(){
		jQuery("#calendar").fullCalendar('removeEvents');
		var classroomId = jQuery("#classroomSelect").val();
		jQuery.ajax({
        	type:"post",
        	dataType:"json",
        	url:"/cms/order/events",
        	async:true,
        	data:{classroom:classroomId},
        	success:function(data) {
        		var resultCollection = jQuery.parseJSON(data.events);
                jQuery.each(resultCollection, function (index, term) {
                	jQuery("#calendar").fullCalendar('renderEvent', term, true);
                });
        	}
        })
	});
	jQuery("#orderClassroomForm").submit(function(e){
	    e.preventDefault();
	  });
	
	jQuery("#order_btn").click(function(){
		var params = jQuery("#orderClassroomForm").serializeArray(); 
		var coursesVal = jQuery("#course_select").val();
		if(coursesVal == null || coursesVal == "") {
			coursesVal = jQuery("#weekCorse").attr("num");
		}
		var courses = {
				name:"courses",
				value:coursesVal
		};
		params.push(courses);
		jQuery.ajax({
			   type: "post",
			   url: "/cms/order/orderRoom",
			   dataType:"json",
			   data: params,
			   success: function(data){
				   if(data.flag == true) {
					   var resultCollection = jQuery.parseJSON(data.events);
		                jQuery.each(resultCollection, function (index, term) {
		                	jQuery("#calendar").fullCalendar('renderEvent', term, true);
		                });
		                jQuery("#classroomOrder_dialog").dialog("close");
		                jQuery.jGrowl("恭喜您，预订成功！");
				   } else {
					   jQuery.jGrowl("很抱歉，预订失败！");
				   }
			   },
				error:function(e) {  
					jQuery.jGrowl("很抱歉，预订失败！");
		        }
			 });
	});
	
	jQuery("#cancel_btn").click(function(){
		var id = jQuery("#order_id").val();
		jQuery.ajax({
			   type: "post",
			   url: "/cms/order/cacelOrder",
			   dataType:"json",
			   data: {id: id},
			   success: function(data){
				   if(data.flag == true) {
					   	jQuery("#calendar").fullCalendar('removeEvents', id);
		                jQuery("#classroomOrder_dialog").dialog("close");
		                jQuery.jGrowl("恭喜您，取消预订成功！");
		                
				   }else {
					   jQuery.jGrowl("很抱歉，取消预订失败！");
				   }
			   },
				error:function(e) {  
					jQuery.jGrowl("很抱歉，取消预订失败！");
		        }
			 });
	});
	
	jQuery("#check_yes_btn").click(function(){
		var id = jQuery("#order_id").val();
		jQuery.ajax({
			   type: "post",
			   url: "/cms/order/pass",
			   dataType:"json",
			   data: {id: id},
			   success: function(data){
				   if(data.flag == true) {
					   	jQuery("#calendar").fullCalendar('removeEvents', id);
					    var resultCollection = jQuery.parseJSON(data.events);
		                jQuery.each(resultCollection, function (index, term) {
		                	jQuery("#calendar").fullCalendar('renderEvent', term, true);
		                });
		                jQuery("#classroomOrder_dialog").dialog("close");
		                jQuery.jGrowl("恭喜您，审核预订通过成功！");
		                
				   }else {
					   jQuery.jGrowl("很抱歉，审核预订通过失败！");
				   }
			   },
				error:function(e) {  
					jQuery.jGrowl("很抱歉，审核预订通过失败！");
		        }
			 });
	});
	
	jQuery("#check_no_btn").click(function(){
		var id = jQuery("#order_id").val();
		jQuery.ajax({
			   type: "post",
			   url: "/cms/order/notPass",
			   dataType:"json",
			   data: {id: id},
			   success: function(data){
				   if(data.flag == true) {
					   	jQuery("#calendar").fullCalendar('removeEvents', id);
		                jQuery("#classroomOrder_dialog").dialog("close");
		                jQuery.jGrowl("恭喜您，审核预订不通过成功！");
		                
				   }else {
					   jQuery.jGrowl("很抱歉，审核预订不通过失败！");
				   }
			   },
				error:function(e) {  
					jQuery.jGrowl("很抱歉，审核预订不通过失败！");
		        }
			 });
	});
	
	
	// /// SWITCHING LIST FROM 3 COLUMNS TO 2 COLUMN LIST /////
	function reposTitle() {
		if (jQuery(window).width() < 450) {
			if (!jQuery('.fc-header-title').is(':visible')) {
				if (jQuery('h3.calTitle').length == 0) {
					var m = jQuery('.fc-header-title h2')
							.text();
					jQuery(
							'<h3 class="calTitle">' + m
									+ '</h3>').insertBefore(
							'#calendar table.fc-header');
				}
			}
		} else {
			jQuery('h3.calTitle').remove();
		}
	}
	reposTitle();
	
	// /// ON RESIZE WINDOW /////
	jQuery(window).resize(function() {
		reposTitle();
	});
	
	
	
	jQuery("#date").datepicker({
		minDate: new Date()
	});
	
	
	
	jQuery('#myOrderTable, #classroomOrderTable').dataTable({
		"sPaginationType": "full_numbers",
		"oLanguage": {
			"sLengthMenu": "每页显示 _MENU_ 条记录",
			"sZeroRecords": "抱歉， 没有找到",
			"sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
			"sInfoEmpty": "没有数据",
			"sInfoFiltered": "(从 _MAX_ 条数据中检索)",
			"sSearch":"全文搜索:",
			"oPaginate": {
			"sFirst": "首页",
			"sPrevious": "前一页",
			"sNext": "后一页",
			"sLast": "尾页",
			},
			"sZeroRecords": "没有检索到数据",
			"sProcessing": "<img src='./loading.gif' />"
		}
	});
	
	jQuery('#checkOrderTable').dataTable({
		"sPaginationType": "full_numbers",
		"oLanguage": {
			"sLengthMenu": "每页显示 _MENU_ 条记录",
			"sZeroRecords": "抱歉， 没有找到",
			"sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
			"sInfoEmpty": "没有数据",
			"sInfoFiltered": "(从 _MAX_ 条数据中检索)",
			"sSearch":"全文搜索:",
			"oPaginate": {
			"sFirst": "首页",
			"sPrevious": "前一页",
			"sNext": "后一页",
			"sLast": "尾页",
			},
			"sZeroRecords": "没有检索到数据",
			"sProcessing": "<img src='./loading.gif' />"
		},
		"aaSortingFixed": [[0,'asc']],
		"fnDrawCallback": function(oSettings) {
            jQuery('input:checkbox,input:radio').uniform();
			//jQuery.uniform.update();
        }
	});
	
	jQuery('input:checkbox,input:radio').uniform();
});

